//
//  SDCountDownButton.m
//  SKinDiary
//
//  Created by pcyang on 16/7/10.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDCountDownButton.h"

@implementation SDCountDownButton
#pragma -mark touche action
-(void)addToucheHandler:(TouchedDownBlock)touchHandler{
    touchedDownBlock = [touchHandler copy];
    [self addTarget:self action:@selector(touched:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)touched:(SDCountDownButton*)sender{
    if (touchedDownBlock) {
        touchedDownBlock(sender,sender.tag);
    }
}

#pragma -mark count down method
-(void)startWithSecond:(int)second
{
    _totalSecond = second;
    _second = _totalSecond;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerStart:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
}
-(void)timerStart:(NSTimer *)theTimer {
    if (_second == 1)
    {
        [self stop];
    }
    else
    {
        _second--;
        if (didChangeBlock)
        {
            [self setTitle:didChangeBlock(self,_second) forState:UIControlStateNormal];
            [self caculateCountDownBtnWidth];
        }
        else
        {
            NSString *title = [NSString stringWithFormat:@"%d秒",_second];
            [self setTitle:title forState:UIControlStateNormal];
           // [self caculateCountDownBtnWidth];
        }
    }
}

- (void)stop{
    if (timer) {
        if ([timer respondsToSelector:@selector(isValid)])
        {
            if ([timer isValid])
            {
                [timer invalidate];
                _second = _totalSecond;
                if (didFinishedBlock)
                {
                    [self setTitle:didFinishedBlock(self,_totalSecond)forState:UIControlStateNormal];
                }
                else
                {
                    [self setTitle:@"重新获取" forState:UIControlStateNormal];
                   // [self caculateCountDownBtnWidth];
                }
            }
        }
    }
}
#pragma -mark block
-(void)didChange:(DidChangeBlock)block{
    didChangeBlock = [didChangeBlock copy];
}
-(void)didFinished:(DidFinishedBlock)block{
    didFinishedBlock = [block copy];
}

-(void)caculateCountDownBtnWidth
{
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
    CGSize size = [self.titleLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, self.frame.size.height) options:NSStringDrawingTruncatesLastVisibleLine attributes:attribute context:nil].size;
    self.width = size.width + 20;
}
@end
